const mongoose = require('mongoose');
const Attendance = mongoose.model('Attendance') || mongoose.model('Attendance', new mongoose.Schema({
  studentId: { type: mongoose.Schema.Types.ObjectId, ref: 'Student', required: true },
  classId: { type: mongoose.Schema.Types.ObjectId, ref: 'Class', required: true },
  date: { type: Date, required: true },
  status: { type: String, required: true, enum: ['present', 'absent', 'late', 'excused'] },
  notes: { type: String },
  createdAt: { type: Date, default: Date.now },
  updatedAt: { type: Date, default: Date.now }
}));

// 考勤控制器
const attendanceController = {
  // 获取所有考勤记录
  async getAllAttendances(ctx) {
    try {
      const attendances = await Attendance.find()
        .populate('studentId classId')
        .sort({ date: -1 });
      ctx.body = {
        success: true,
        data: attendances,
        count: attendances.length
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取考勤记录失败',
        error: error.message
      };
    }
  },

  // 根据ID获取考勤记录
  async getAttendanceById(ctx) {
    try {
      const attendance = await Attendance.findById(ctx.params.id)
        .populate('studentId classId');
      if (!attendance) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '考勤记录不存在'
        };
        return;
      }
      ctx.body = {
        success: true,
        data: attendance
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取考勤信息失败',
        error: error.message
      };
    }
  },

  // 创建考勤记录
  async createAttendance(ctx) {
    try {
      const { studentId, classId, date, status, notes } = ctx.request.body;

      // 检查是否已有该学生当天的考勤记录
      const existingAttendance = await Attendance.findOne({
        studentId,
        date: new Date(date).setHours(0, 0, 0, 0)
      });
      if (existingAttendance) {
        ctx.status = 400;
        ctx.body = {
          success: false,
          message: '该学生当天的考勤记录已存在'
        };
        return;
      }

      // 创建考勤记录
      const attendance = new Attendance({
        studentId,
        classId,
        date: new Date(date),
        status,
        notes
      });
      await attendance.save();
      
      // 重新获取考勤信息（包含关联数据）
      const newAttendance = await Attendance.findById(attendance._id)
        .populate('studentId classId');

      ctx.status = 201;
      ctx.body = {
        success: true,
        message: '考勤记录创建成功',
        data: newAttendance
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '创建考勤记录失败',
        error: error.message
      };
    }
  },

  // 批量创建考勤记录
  async batchCreateAttendances(ctx) {
    try {
      const { classId, date, records } = ctx.request.body;
      const attendanceDate = new Date(date);
      const formattedDate = new Date(attendanceDate).setHours(0, 0, 0, 0);
      
      // 先删除该班级当天的所有考勤记录
      await Attendance.deleteMany({
        classId,
        date: formattedDate
      });
      
      // 创建新的考勤记录
      const newAttendances = records.map(record => ({
        studentId: record.studentId,
        classId,
        date: attendanceDate,
        status: record.status,
        notes: record.notes || ''
      }));
      
      const result = await Attendance.insertMany(newAttendances);
      
      ctx.status = 201;
      ctx.body = {
        success: true,
        message: '批量考勤记录创建成功',
        count: result.length
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '批量创建考勤记录失败',
        error: error.message
      };
    }
  },

  // 更新考勤记录
  async updateAttendance(ctx) {
    try {
      const attendance = await Attendance.findById(ctx.params.id);
      if (!attendance) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '考勤记录不存在'
        };
        return;
      }

      const updateData = ctx.request.body;
      // 更新考勤信息
      Object.assign(attendance, updateData);
      attendance.updatedAt = Date.now();
      await attendance.save();

      // 重新获取考勤信息（包含关联数据）
      const updatedAttendance = await Attendance.findById(ctx.params.id)
        .populate('studentId classId');

      ctx.body = {
        success: true,
        message: '考勤信息更新成功',
        data: updatedAttendance
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '更新考勤信息失败',
        error: error.message
      };
    }
  },

  // 删除考勤记录
  async deleteAttendance(ctx) {
    try {
      const attendance = await Attendance.findById(ctx.params.id);
      if (!attendance) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '考勤记录不存在'
        };
        return;
      }

      // 删除考勤记录
      await Attendance.findByIdAndDelete(ctx.params.id);

      ctx.body = {
        success: true,
        message: '考勤记录删除成功'
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '删除考勤记录失败',
        error: error.message
      };
    }
  },

  // 获取学生的考勤记录
  async getStudentAttendances(ctx) {
    try {
      const { studentId } = ctx.params;
      const startDate = ctx.query.startDate ? new Date(ctx.query.startDate) : null;
      const endDate = ctx.query.endDate ? new Date(ctx.query.endDate) : null;
      
      const query = { studentId };
      if (startDate) {
        query.date = { $gte: startDate };
      }
      if (endDate) {
        query.date = query.date || {};
        query.date.$lte = endDate;
      }
      
      const attendances = await Attendance.find(query)
        .populate('classId')
        .sort({ date: -1 });
      
      // 计算考勤统计
      const stats = {
        total: attendances.length,
        present: 0,
        absent: 0,
        late: 0,
        excused: 0
      };
      
      attendances.forEach(record => {
        stats[record.status]++;
      });
      
      ctx.body = {
        success: true,
        data: {
          attendances,
          stats
        }
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取学生考勤记录失败',
        error: error.message
      };
    }
  },

  // 获取班级的考勤记录
  async getClassAttendances(ctx) {
    try {
      const { classId } = ctx.params;
      const date = ctx.query.date ? new Date(ctx.query.date) : null;
      
      const query = { classId };
      if (date) {
        const formattedDate = new Date(date).setHours(0, 0, 0, 0);
        query.date = formattedDate;
      }
      
      const attendances = await Attendance.find(query)
        .populate('studentId')
        .sort({ studentId: 1 });
      
      ctx.body = {
        success: true,
        data: attendances,
        count: attendances.length
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取班级考勤记录失败',
        error: error.message
      };
    }
  },

  // 获取指定日期的考勤记录
  async getAttendancesByDate(ctx) {
    try {
      const date = new Date(ctx.params.date);
      const formattedDate = new Date(date).setHours(0, 0, 0, 0);
      
      const attendances = await Attendance.find({
        date: formattedDate
      })
        .populate('studentId classId')
        .sort({ classId: 1, studentId: 1 });
      
      ctx.body = {
        success: true,
        data: attendances,
        count: attendances.length
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取指定日期考勤记录失败',
        error: error.message
      };
    }
  },

  // 获取班级考勤统计信息
  async getClassAttendanceStats(ctx) {
    try {
      const { classId } = ctx.params;
      const startDate = ctx.query.startDate ? new Date(ctx.query.startDate) : null;
      const endDate = ctx.query.endDate ? new Date(ctx.query.endDate) : null;
      
      const query = { classId };
      if (startDate) {
        query.date = { $gte: startDate };
      }
      if (endDate) {
        query.date = query.date || {};
        query.date.$lte = endDate;
      }
      
      const attendances = await Attendance.find(query);
      
      // 计算统计信息
      const stats = {
        totalRecords: attendances.length,
        statusCounts: {
          present: 0,
          absent: 0,
          late: 0,
          excused: 0
        },
        attendanceRate: '0%'
      };
      
      attendances.forEach(record => {
        stats.statusCounts[record.status]++;
      });
      
      // 计算出勤率
      const totalPossible = stats.statusCounts.present + stats.statusCounts.absent + stats.statusCounts.late;
      if (totalPossible > 0) {
        const presentAndExcused = stats.statusCounts.present + stats.statusCounts.excused;
        stats.attendanceRate = `${((presentAndExcused / totalPossible) * 100).toFixed(1)}%`;
      }
      
      ctx.body = {
        success: true,
        data: stats
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取班级考勤统计失败',
        error: error.message
      };
    }
  }
};

module.exports = attendanceController;